<template>
  <div>
    <el-button v-if="!disabled" class="button-new-tag" icon="el-icon-plus" size="small" @click="open()">
      选择标签
    </el-button>
    <div style="margin-bottom: 10px;">
      <div v-for="(item, index) in value" :key="index">
        {{item.pName}}/{{item.label}}
        <el-button size="mini" type="text" @click="value.splice(index, 1)">删除</el-button>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :visible.sync="visible" :title="dialogTitle" width="1100px">
      <div style="display: flex;justify-content: space-between">
        <div class="left">
          <NormalForm :formList="formList" :is-noinfo.sync="isNoInfo"
                      :isShowCard="false" :operateForm="queryForm" style="position: relative"
                      @handleReset="handleReset" @specialSearch="handleQuery"></NormalForm>
          <div v-loading="loading">
            <div class="tree-head">
              <div class="tree-head-check">
                <el-checkbox v-model="checkAll" @change="onCheckAllChange"></el-checkbox>
              </div>
              <div class="tree-head-one">标签</div>
            </div>
            <el-tree ref="treeTable" :data="treeData" :default-expand-all="true"
                     :props="treeDefaultProps" node-key="id"
                     show-checkbox @check="onCheckTree">
				        <span slot-scope="{ node, data }" class="tree-custom-node">
					        <span style="flex: 1;">{{ node.label }}{{ node.level == '2' ? `(${data.count})` : ''}}</span>
				        </span>
            </el-tree>
          </div>
        </div>
        <div class="right">
          <div class="right-info">总计{{ checkedList.length || 0 }}个标签</div>
          <div class="right-tag">
            <div>
              <div v-for="(item,index) in checkedList" :key="item.id">
                <el-tag closable @close="handleTagClose(item,index)">{{item.pName}}/{{item.label}}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="ok">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {groupLabelNew} from "@/api/dispatchCustomer";

export default {
  name: 'selectTableLabel',
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    queryOptions: {
      type: Array,
      default() {
        return []
      }
    },
    dialogTitle: {
      type: String,
      default: '选择标签',
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      checkAll: false,
      loading: false,
      treeData: [],
      dataArr: [],
      treeDefaultProps: {
        children: 'children',
        label: 'label'
      },
      treeSelArr: [],
      treeLength: 0,
      visible: false,
      queryForm: {
        labelName: '',
        pageNum: 1,
        pageSize: 9999,
      },
      formList: [
        {
          label: '标签名称',
          value: '',
          prop: 'labelName',
          type: 'INPUT',
          emunName: '',
          xs: 24,
          ls: 24,
          md: 24,
          lg: 24,
          xl: 24,
        },
      ],
      isNoInfo: false,
      checkedList: []
    };
  },
  created() {
  },
  methods: {
    open() {
      this.queryForm.labelName = ''
      this.getListFn('1')
      this.visible = true;
      console.log(this.queryOptions, 'queryOptions')
    },
    ok() {
      this.$emit('change', this.checkedList)
      this.visible = false
    },
    // 初始化树的长度
    initTreeLengh(arr) {
      let count = 0;
      arr.map(item => {
        if (item.children) {
          count += item.children.length;
        }
      });
      this.treeLength = count + arr.length;
    },
    // 全选改变时
    onCheckAllChange() {
      if (this.checkAll) {
        this.$refs.treeTable.setCheckedNodes(this.treeData);
      } else {
        this.$refs.treeTable.setCheckedKeys([]);
      }
      this.onCheckTree()
    },
    // 节点选中状态发生变化时的回调
    onCheckTree() {
      this.treeSelArr = [];
      this.treeSelArr = this.$refs.treeTable.getCheckedNodes();
      let arr1 = JSON.parse(JSON.stringify(this.treeSelArr));
      console.log('12343321', this.treeSelArr);
      let arr = new Array();
      arr = arr1.filter(item => item.level != '1');
      // arr = this.checkedList.concat(arr);
      this.checkedList = Array.from(arr.reduce((map, obj) => map.set(obj.id, obj), new Map()).values());
      console.log(this.checkedList, 'checkedList');
      this.treeSelArr.length == this.treeLength ? (this.checkAll = true) : (this.checkAll = false);
    },
    handleReset() {
      this.queryForm = {
        labelName: "",
      };
      this.getListFn();
    },
    handleQuery() {
      console.log('是这里吗')
      this.getListFn()
    },
    async getListFn(val) {
      console.log('没有触发???')
      const id = this.queryOptions?.[0]?.weUserId
      if (id) {
        const res = await groupLabelNew({weUserId: id, labelName: this.queryForm.labelName})
        if (res.code === 200) {
          this.treeData = res?.data?.map(item => {
            return {
              ...item,
              id: item.groupId,
              label: item.name,
              level: '1',
              children: item?.children?.map(itm => {
                return {
                  ...itm,
                  id: itm.value,
                  label: itm.name,
                  pid: item.groupId,
                  pName: item.name,
                  level: '2',
                  count: itm?.count || 0,
                }
              })
            }
          })
          console.log(this.treeData, 'treeData')
          this.$set(this, 'treeData', this.treeData)
          this.treeSelArr = []
          this.checkedList = []
          if(val == '1') {
            this.dataArr = JSON.parse(JSON.stringify(this.treeData))
            let arr = JSON.parse(JSON.stringify(this.value))
            this.checkedList = arr
            this.$refs.treeTable.setCheckedKeys(arr.map(item => item.id))
          }
          this.initTreeLengh(this.treeData)
          this.treeSelArr.length == this.treeLength ? (this.checkAll = true) : (this.checkAll = false);
        }
      }
    },
    handleTagClose(val,index){
      this.checkedList.splice(index, 1)
      let arr = JSON.parse(JSON.stringify(this.treeSelArr))
      this.treeSelArr = arr.filter(item => {
        if(item.id == val.pid && item.children.length == 1) return false
        if(item.id == val.id) return false
      })
      console.log(this.treeSelArr, 'handleTagClose')
      this.$refs.treeTable.setChecked(val.id, false);
    },
  }
};
</script>

<style lang="scss" scoped>
/*处理css, 使用 scss, 加上 scoped*/

.tree-head {
  width: 400px;
  background-color: #f8f8f8;
  line-height: 40px;
  height: 40px;
  border: 1px solid #dcdee3;
  border-bottom: none;
  display: flex;
  font-size: 14px;
  color: #606266;
  padding-right: 8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.tree-head-check {
  width: 38px;
  text-align: right;
}

.tree-head-one {
  flex: 1;
}

.tree-head-one {
  padding-left: 8px;
}

.tree-custom-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

::v-deep {
  .el-tree {
    overflow-y: auto;
    overflow-x: hidden;
    width: 400px;
    max-height: 500px;
    border: 1px solid #dcdee3;
    //border: 0!important;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }

  .el-tree .el-tree-node {
    //border: 1px solid #dcdee3;
    border: 0;
    border-bottom: none;
  }

  .el-tree {
    //border-bottom: 1px solid #dcdee3;
  }

  .el-tree-node__children .el-tree-node {
    border: none;
  }

  .el-tree-node__content {
    line-height: 40px !important;
    height: 40px !important;
    position: relative;
    padding-left: 24px!important;
    .el-tree-node__expand-icon.expanded{
      position: absolute;
      right: 30px;
      font-size: 18px;
    }
    .el-tree-node__expand-icon{
      position: absolute;
      right: 30px;
      font-size: 18px;
    }
  }
  .el-tree-node.is-expanded > .el-tree-node__children {
    display: block;
    padding-left: 24px;
    //border-top: 1px solid #dcdee3;
  }

  .el-tree-node__children .el-tree-node__content {
    //border-top: 1px solid #dcdee3;
    //border-top: 1px solid #dcdee3;
    border-bottom: 0;
  }

  .el-tree-node:focus > .el-tree-node__content {
    background-color: #ffffff !important;
  }
}

.right {
  flex: 1;
  border-radius: 8px;
  margin-left: 30px;
  display: flex;
  flex-direction: column;
}

.right-info {
  padding: 16px 10px;
  line-height: 53px;
}

.right-tag {
  border: 1px solid #dcdee3;
  border-radius: 2px;
  flex: 1;
  div{
    display: flex;
    flex-wrap: wrap;
    div{
      margin: 10px 0 0 10px;
    }
  }
  position: relative;
  &::before{
    content: '';
    display: block;
    width: 1px;
    position: absolute;
    left: -15px;
    border-left: 1px solid #dcdee3;
    height: 100%;
  }
}
</style>
